package com.cylise.coolweather;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cylise.coolweather.db.City;
import com.cylise.coolweather.db.Country;
import com.cylise.coolweather.db.Province;
import com.cylise.coolweather.db.Town;
import com.cylise.coolweather.util.DbUtil;
import com.cylise.coolweather.util.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Cylise on 2016/12/27.
 */

public class ChooseFragment extends Fragment {
    Button backButton;
    TextView provinceTextView;
    ListView listView;
    ArrayAdapter adapter;
    ProgressDialog progressDialog;
    private final int PROVINCENOW = 0;
    private final int CITYNOW = 1;
    private final int COUNTRYNOW = 2;
    private int status;
    List<Province> provinces;
    List<City> cities;
    List<Country> countries;
    List<Town> towns;
    private Town selectedtown;
    private Province selectedProvince;
    private City selectedCity;
    private Country selectedCountry;
    private ArrayList<String> dataList = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
/*      Random rand = new Random(50);
        for (int i = 0;i<50;i++){
            dataList.add(rand.nextInt(50)+"");
        }*/
        status = PROVINCENOW;
        View view = inflater.inflate(R.layout.choose_fragment, container, false);
        backButton = (Button) view.findViewById(R.id.back_button);
        provinceTextView = (TextView) view.findViewById(R.id.titlename);
        listView = (ListView) view.findViewById(R.id.listname);
        adapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (status == PROVINCENOW) {
                    selectedProvince = provinces.get(position);
                    queryCities();
                } else if (status == CITYNOW) {
                    selectedCity = cities.get(position);
                    queryCountries();
                } else {
                    selectedCountry = countries.get(position);
                    //Toast.makeText(getContext(),selectedCountry.getWeather_id(),Toast.LENGTH_SHORT).show();
                    String weatherId = selectedCountry.getWeather_id();

                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("weather", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("weatherId", weatherId);
                    editor.apply();

                    startWeatherActivity(weatherId);
                    //启动指定县的天气预报
                }
            }

        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status == COUNTRYNOW) {
                    queryCities();
                } else if (status == CITYNOW) {
                    queryProvinces();
                }
            }
        });

        queryProvinces();
        return view;
    }


    public void startWeatherActivity(String weatherId) {
        Intent intent = new Intent(getActivity(), WeatherActivity.class);
        intent.putExtra("weatherId", weatherId);
        startActivity(intent);
    }

    private void queryProvinces() {
        provinceTextView.setText("全国");
        backButton.setVisibility(View.GONE);
        showProgressDialog();
        towns = DataSupport.select("ProvinceZh")
                .where("countryZh = ?", "中国")
                .find(Town.class);

        if (towns.isEmpty()) {
            Log.d("town", "getDB");
            HttpUtil.sendOKHttpRequest(getResources().getString(R.string.url), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "城市列表加载失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    Gson gson = new Gson();
                    List<Town> towns;
                    towns = gson.fromJson(body, new TypeToken<List<Town>>() {}.getType());
                    if (!towns.isEmpty()) {
                        Log.d("town", "GetTown");
                        DataSupport.saveAll(towns);
                        /*for (Town town:towns){
                            Log.d("town",town.getCityZh());
                            town.saveFast();
                        }*/

                        dataList.clear();
                   /*获取省信息*/
                        Log.d("town", "GetPro");
                        String sql = "select provinceZh from Town where countryZh='中国' group by provinceZh";
                        Cursor cursor = DataSupport.findBySQL(sql);
                        while (cursor.moveToNext()) {
                            Province province = new Province();
                            province.setName(cursor.getString(0));
                            dataList.add(cursor.getString(0));
                            province.saveFast();
                        }
                        cursor.close();

                        provinces = DataSupport.findAll(Province.class);

                        Log.d("town", "haveDB");



                   /*获取地市信息*/
                        Log.d("town", "GetCity");
                        sql = "select provinceZh,leaderZh from Town where countryZh='中国' group by provinceZh,leaderZh";
                        cursor = DataSupport.findBySQL(sql);
                        while (cursor.moveToNext()) {
                            City city = new City();
                            city.setProvince(cursor.getString(0));
                            city.setName(cursor.getString(1));
                            city.saveFast();
                        }
                        cursor.close();

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetInvalidated();
                                closeProgressDialog();
                            }
                        });
                        status = PROVINCENOW;

                   /*获取县信息*/
                        /*Log.d("town","GetCountry");
                        sql="select cnId,leaderZh,cityZh from Town where countryZh='中国'";
                        cursor= DataSupport.findBySQL(sql);
                        cursor.moveToFirst();
                        while (cursor.moveToNext()){
                            Country country = new Country();
                            country.setWeather_id(cursor.getString(0));
                            country.setName(cursor.getString(2));
                            country.setCity(cursor.getString(1));
                            country.saveFast();
                        }
                        cursor.close();*/


                    }

                }

            });
        } else {
            provinces = DataSupport.findAll(Province.class);

            Log.d("town", "haveDB");
            dataList.clear();
            for (Province province : provinces) {
                dataList.add(province.getName());
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetInvalidated();
                    closeProgressDialog();
                }
            });
            status = PROVINCENOW;
        }

    }

    private void queryCities() {
        provinceTextView.setText(selectedProvince.getName());
        backButton.setVisibility(View.VISIBLE);
        cities = DataSupport.where("province = ?", selectedProvince.getName()).find(City.class);
        if (cities.isEmpty()) {
            /*HttpUtil.sendOKHttpRequest(getResources().getString(R.string.url), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    Gson gson=new Gson();
                    cities = gson.fromJson(body,new TypeToken<List<City>>(){}.getType());
                    if (!cities.isEmpty()){
                        dataList.clear();
                        for (City city:cities){
                            String s = city.getName();
                            dataList.add(s);
                            city.setProvinceId(selectedProvince.getId());
                            city.setCityCode(city.getId());
                            city.save();

                        }


                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetInvalidated();
                            status = CITYNOW;
                        }
                    });

                }
            });*/
        } else {
            dataList.clear();
            for (City city : cities) {
                String s = city.getName();
                dataList.add(s);
            }
            adapter.notifyDataSetInvalidated();

        }
        status = CITYNOW;

    }

    private void queryCountries() {
        provinceTextView.setText(selectedCity.getName());
        backButton.setVisibility(View.VISIBLE);
        countries = DataSupport.where(" city= ?", selectedCity.getName()).find(Country.class);
        if (countries.isEmpty()) {

            /*获取县信息*/

            String sql = "select cnId,leaderZh,cityZh from Town where  leaderZh='" + selectedCity.getName() + "'";
            //Log.d("town", "GetCountry:"+sql);
            Cursor cursor = DataSupport.findBySQL(sql);
            while (cursor.moveToNext()) {
                Log.d("country", cursor.getString(2));
                Country country = new Country();
                country.setWeather_id(cursor.getString(0));
                country.setName(cursor.getString(2));
                country.setCity(cursor.getString(1));
                country.saveFast();
            }
            cursor.close();

            countries = DataSupport.where(" city= ?", selectedCity.getName()).find(Country.class);
            dataList.clear();
            for (Country country : countries) {
                String s = country.getName();
                dataList.add(s);
            }
        }


            /*HttpUtil.sendOKHttpRequest(getResources().getString(R.string.url)+"/"+selectedProvince.getPorvinceCode()+"/"+selectedCity.getCityCode(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    Gson gson=new Gson();
                    countries = gson.fromJson(body,new TypeToken<List<Country>>(){}.getType());
                    if (!countries.isEmpty()){
                        dataList.clear();
                        for (Country country:countries){
                            String s = country.getName();
                            dataList.add(s);
                            country.setCityId(selectedCity.getCityCode());
                            country.save();
                        }

                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetInvalidated();
                            status = COUNTRYNOW;
                        }
                    });

                }
            });*/
        else {
            dataList.clear();
            for (Country country : countries) {
                String s = country.getName();
                dataList.add(s);
            }


        }
        Log.d("town", "HaveCountry");
        adapter.notifyDataSetInvalidated();
        status = COUNTRYNOW;
    }

    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog= new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载城市列表...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }

}
